#!/bin/bash

# GPT-AI 应用部署脚本
APP_NAME="gpt-ai"
APP_HOME="/home/admin/app"
JAR_FILE="${APP_HOME}/target/gpt-ai-0.0.1-SNAPSHOT.jar"
PID_FILE="${APP_HOME}/app.pid"

# 创建必要目录
mkdir -p ${APP_HOME}/logs

# 停止应用
stop() {
    echo "Stopping $APP_NAME..."
    if [ -f $PID_FILE ]; then
        PID=$(cat $PID_FILE)
        if ps -p $PID > /dev/null 2>&1; then
            kill -15 $PID
            sleep 5
            if ps -p $PID > /dev/null 2>&1; then
                kill -9 $PID
            fi
        fi
        rm -f $PID_FILE
    fi
    echo "Stopped $APP_NAME"
}

# 启动应用
start() {
    echo "Starting $APP_NAME..."
    if [ ! -f "$JAR_FILE" ]; then
        echo "Error: JAR file not found at $JAR_FILE"
        exit 1
    fi
    
    cd $APP_HOME
    nohup java -jar $JAR_FILE > logs/app.log 2>&1 &
    echo $! > $PID_FILE
    echo "Started $APP_NAME with PID: $(cat $PID_FILE)"
}

# 重启应用
restart() {
    stop
    sleep 2
    start
}

# 检查状态
status() {
    if [ -f $PID_FILE ]; then
        PID=$(cat $PID_FILE)
        if ps -p $PID > /dev/null 2>&1; then
            echo "$APP_NAME is running with PID: $PID"
        else
            echo "$APP_NAME is not running"
        fi
    else
        echo "$APP_NAME is not running"
    fi
}

# 主逻辑
case "$1" in
    start)
        start
        ;;
    stop)
        stop
        ;;
    restart)
        restart
        ;;
    status)
        status
        ;;
    *)
        echo "Usage: $0 {start|stop|restart|status}"
        exit 1
        ;;
esac